<?php

namespace app\admin\controller\xykeep;

use app\common\controller\Backend;
use app\admin\model\xykeep\distribution\Commission as CommissionModel;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 分销商
 *
 * @icon fa fa-circle-o
 */
class Distribution extends Backend
{

    /**
     * Distribution模型对象
     * @var \app\admin\model\xykeep\Distribution
     */
    protected $model = null;
    protected $searchFields = 'user_id,user.nickname,user.mobile';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xykeep\Distribution;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    public function team($distribution_id = '')
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['user','level'])
            ->where($where)
            ->where('pid',$distribution_id)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['user','parent','level'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 详情
     *
     * @param $id
     */
    public function detail($user_id = null)
    {
        $row = $this->model->with(['user','level','parent'])->where(['user_id'=>$user_id])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 调整佣金
     *
     * @param $id
     */
    public function recharge($user_id = null)
    {
        $row = $this->model->where(['user_id'=>$user_id])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $before = $row['commission'];
            $after = $row['commission']+$params['num'];

            $data = ['commission'=>$after];
            if($params['num']>0){
                $data['total_commission'] = $row['total_commission'] + $params['num'];
            }

            $row->allowField(true)->save($data);
            $result = CommissionModel::create([
                'distribution_id' => $row['user_id'],
                'type'    => 'sys',
                'money'    => $params['num'],
                'before'    => $before,
                'after'    => $after,
                'remark'   => $params['remark']
            ]);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
